﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Web.Administration;

namespace SBPweb.RIA.Server.Common.Hosting
{

    public static class SiteManager
    {

        public static IEnumerable<SiteBinding> GetBindings()
        {
            // Get the Site name  
            string siteName = System.Web.Hosting.HostingEnvironment.SiteName;

            // Get the sites section from the AppPool.config 
            ConfigurationSection sitesSection = WebConfigurationManager.GetSection(null, null, "system.applicationHost/sites");

            foreach (ConfigurationElement site in sitesSection.GetCollection())
            {
                // Find the right Site 
                if (String.Equals((string)site["name"], siteName, StringComparison.OrdinalIgnoreCase))
                {
                    // For each binding see if they are http based and return the port and protocol 
                    foreach (ConfigurationElement binding in site.GetCollection("bindings"))
                    {
                        string protocol = (string)binding["protocol"];
                        string bindingInfo = (string)binding["bindingInformation"];

                        if (protocol.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                        {
                            string[] parts = bindingInfo.Split(':');
                            if (parts.Length == 3)
                            {
                                string ip = parts[0];
                                string port = parts[1];
                                string host = parts[2];
                                yield return new SiteBinding(protocol, ip, host, port);
                            }
                        }
                    }
                }
            }
        }

    }

}